package com.sx.pipeline.view.imageupload;

import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.hjq.widget.view.MaxHeightRecyclerView;
import com.kunminx.binding_recyclerview.adapter.SimpleDataBindingAdapter;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.OnImageViewerLongPressListener;
import com.lxj.xpopup.util.SmartGlideImageLoader;
import com.sx.pipeline.R;
import com.sx.pipeline.databinding.ItemImageUploadBinding;
import com.sx.pipeline.utils.DiffUtils;
import com.sx.pipeline.utils.RxViewUntil;


import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description 图片上传
 * @Author 梁浩文
 * @Date 2021/6/15 13:57
 */
public class ImageUploadView extends MaxHeightRecyclerView {
    private int rowCount;
    private int maxCount;
    private ImageUploadListener imageUploadListener;
    private ImageUploadAdapter imageUploadAdapter;
    private List<String> adapterData;

    public void setImageUploadListener(ImageUploadListener imageUploadListener) {
        this.imageUploadListener = imageUploadListener;
    }

    public ImageUploadView(@NonNull Context context) {
        super(context);
    }

    public ImageUploadView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }


    /**
     * 初始化适配器
     *
     * @param rowCount 一行多少个
     * @param maxCount 最大容量
     */
    public void initAdapter(int rowCount, int maxCount) {
        this.rowCount = rowCount;
        this.maxCount = maxCount;
        getItemAnimator().setAddDuration(0);
        getItemAnimator().setChangeDuration(0);
        getItemAnimator().setMoveDuration(0);
        getItemAnimator().setRemoveDuration(0);
        adapterData = new ArrayList<>();
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), rowCount);
        setLayoutManager(gridLayoutManager);
        imageUploadAdapter = new ImageUploadAdapter(getContext());
        setAdapter(imageUploadAdapter);
        adapterData.add("");
        imageUploadAdapter.submitList(adapterData);
        LineManagers.LineManagerFactory lineManagerFactory = LineManagers.dividerMargin(DividerMargin.DIVIDER_Left_RIGHT, 7);
        addItemDecoration(lineManagerFactory.create(this));

    }

    protected void deleteImage(int position) {
        boolean isMax = getImagePath().size() == maxCount;
        adapterData.remove(position);
        if (isMax) {
            adapterData.add("");
        }
        imageUploadAdapter.submitList(adapterData);
    }

    public void addImage(String image) {
        List<String> imagePath = getImagePath();
        imagePath.add(image);
        notifyItemChanged(imagePath);
    }

    public void clearImage() {
        List<String> imagePath = getImagePath();
        imagePath.clear();
        notifyItemChanged(imagePath);
    }

    public void notifyItemChanged(List<String> image) {
        try {
            if (image.size() > maxCount) {
                throw new IndexOutOfBoundsException("超出最大的容量" + maxCount);
            } else if (image.size() != maxCount) {
                image.add("");
            }
            adapterData = image;
            imageUploadAdapter.submitList(adapterData);
        } catch (Exception e) {
            throw new IndexOutOfBoundsException("超出最大的容量" + maxCount);
        }

    }


    public List<String> getImagePath() {
        ArrayList<String> path = new ArrayList<>();
        for (String adapterDatum : adapterData) {
            if (!TextUtils.isEmpty(adapterDatum)) {
                path.add(adapterDatum);
            }
        }
        return path;
    }

    public class ImageUploadAdapter extends SimpleDataBindingAdapter<String, ItemImageUploadBinding> {

        public ImageUploadAdapter(Context context) {
            super(context, R.layout.item_image_upload, DiffUtils.getInstance().getStringItemCallback());
        }

        @Override
        protected void onBindItem(ItemImageUploadBinding binding, String item, RecyclerView.ViewHolder holder) {
            int itemCount = getItemCount();
            if (TextUtils.isEmpty(item)) {
                binding.itemImagePath.setVisibility(GONE);
                binding.itemBgUpload.setVisibility(VISIBLE);
                binding.itemImageClose.setVisibility(GONE);
                binding.itemImageCamera.setVisibility(VISIBLE);
                binding.itemTvCamera.setVisibility(VISIBLE);
            } else {
                binding.itemBgUpload.setVisibility(GONE);
                binding.itemImageCamera.setVisibility(GONE);
                binding.itemTvCamera.setVisibility(GONE);
                binding.itemImagePath.setVisibility(VISIBLE);
                binding.itemImageClose.setVisibility(VISIBLE);
                Log.d("fdsafd",item);
                if (item.startsWith("http")){
                    Glide.with(getContext()).load(item).into(binding.itemImagePath);
                }else {
                    File file = new File(item);
                    Glide.with(getContext()).load(file).into(binding.itemImagePath);
                }

            }
            //点击事件
            RxViewUntil.setClickShake(holder.itemView, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (TextUtils.isEmpty(item)) {
                        //添加图片
                        if (imageUploadListener != null) {
                            imageUploadListener.clickAdd();
                        }
                    } else {
                        //查看图片
                        new XPopup.Builder(getContext())
                                .isDestroyOnDismiss(true)
                                .asImageViewer(binding.itemImagePath, item, false, Color.parseColor("#f1f1f1"), -1, 0
                                        , false, Color.BLACK, new SmartGlideImageLoader(com.luck.picture.lib.R.drawable.ps_image_placeholder), new OnImageViewerLongPressListener() {
                                            @Override
                                            public void onLongPressed(BasePopupView popupView, int position) {
                                            }
                                        })
                                .show();
                    }
                }
            });
            RxViewUntil.setClickShake(binding.itemImageClose, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    deleteImage(holder.getLayoutPosition());
                }
            });
        }
    }

    public interface ImageUploadListener {
        void clickAdd();
    }
}
